/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.math.BigInteger;
import java.security.*;
import model.Thanhvien;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import util.HibernateUtil;
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.swing.filechooser.FileSystemView;
import model.Chitietdaugia;
import model.Thanhtoan;
import model.Thanhvienvipham;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.hibernate.SessionFactory;

/**
 *
 * @author HoangLiem
 */
public class ThanhVienDAO {

    public static ArrayList<Thanhvien> getAllUsers() {
        ArrayList<Thanhvien> list = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            Transaction trans = session.getTransaction();
            trans.begin();
            String hql = "from Thanhvien";
            Query query = session.createQuery(hql);
            list = (ArrayList<Thanhvien>) query.list();
            trans.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return list;
    }

    public static Thanhvien logIn(String tenDangNhap, String matKhau) {
        Thanhvien tv = null;
        try {
            try {
                MessageDigest md5 = MessageDigest.getInstance("MD5");
                md5.update(matKhau.getBytes());
                BigInteger dis = new BigInteger(1, md5.digest());
                //byte []dis=md5.digest();
                matKhau = dis.toString(16);
            } catch (NoSuchAlgorithmException e) {
                System.out.print("Loi khong ma hoa duoc bang giai thuat MD5");
            }
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            Transaction trans = session.getTransaction();
            trans.begin();
            String hql = "from Thanhvien tv where tv.tenDangNhap=:tenDangNhap and tv.matKhau=:matKhau";
            Query query = session.createQuery(hql);
            query.setString("tenDangNhap", tenDangNhap);
            query.setString("matKhau", matKhau);
            tv = (Thanhvien) query.uniqueResult();
            trans.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return tv;
    }

    public static Thanhvien getUserById(String tenDangNhap) {
        Thanhvien tv = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            Transaction trans = session.getTransaction();
            trans.begin();
            String hql = "from Thanhvien tv where tv.tenDangNhap=:tenDangNhap ";
            Query query = session.createQuery(hql);
            query.setString("tenDangNhap", tenDangNhap);
            tv = (Thanhvien) query.uniqueResult();
            trans.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return tv;
    }

    public static boolean insertUser(Thanhvien tv) {
        boolean result = false;
        SessionFactory ssFac = HibernateUtil.getSessionFactory();
        Session ss = ssFac.openSession();
        Transaction trans = ss.getTransaction();
        if (!isNumber(tv.getDienThoai())) {
            tv.setDienThoai(null);
        }
        try {
            trans.begin();
            ss.merge(tv);
            result = true;
            ss.flush();
            trans.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
            result = false;
        }
        ssFac.close();
        return result;
    }

    public static Boolean quenMatKhau(String emailTo, String path) {
        Boolean rs = true;
        try {
            ArrayList<String> dskq = new ArrayList<String>();
            dskq = resetPass(emailTo);
            VelocityEngine ve = new VelocityEngine();
            Properties properties = new Properties();
            properties.setProperty("file.resource.loader.path", path);
            ve.init(properties);
            /* get the Template  */
            Template t = ve.getTemplate("test.vm");
            VelocityContext context = new VelocityContext();
            context.put("username", dskq.get(1));
            context.put("newpass", dskq.get(0));

            StringWriter writer = new StringWriter();
            t.merge(context, writer);
            send("smtp.gmail.com", emailTo, "ibidvn.team@gmail.com", "javaphantan2011", "Change your password on ibid.vn", writer.toString());
            //System.out.println(writer.toString());
        } catch (Exception ex) {
            rs = false;
        }
        return rs;
    }

    public static Boolean send(String smtpServer, String to, String from, String psw,
            String subject, String body) {
        Boolean rs = true;
        try {
            Properties props = System.getProperties();
            props.put("mail.smtp.host", smtpServer);
            props.put("mail.smtp.port", "587");
            props.put("mail.smtp.starttls.enable", "true");
            final String login = from;
            final String pwd = psw;
            Authenticator pa = null;
            if (login != null && pwd != null) {
                props.put("mail.smtp.auth", "true");
                pa = new Authenticator() {

                    public PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(login, pwd);
                    }
                };
            }//else: no authentication
            javax.mail.Session session = javax.mail.Session.getInstance(props, pa);
// — Create a new message –
            Message msg = new MimeMessage(session);
// — Set the FROM and TO fields –
            msg.setFrom(new InternetAddress(from));
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(
                    to, false));

// — Set the subject and body text –
            msg.setSubject(subject);
            msg.setContent(body, "text/html");
// — Set some other header information –
            msg.setHeader("X-Mailer", "LOTONtechEmail");
            msg.setSentDate(new Date());
            msg.saveChanges();
// — Send the message –
            Transport.send(msg);
            System.out.println("Mail da duoc gui");
        } catch (Exception ex) {
            rs = false;
        }
        return rs;
    }

    public static ArrayList<String> resetPass(String email) {
        ArrayList<String> dskq = new ArrayList<String>();
        String newpass = getRandomString(3, 6);
        dskq.add(newpass);
        SessionFactory ssFac = HibernateUtil.getSessionFactory();
        try {
            Session ss = ssFac.openSession();
            Transaction trans = ss.getTransaction();
            String hql = "from Thanhvien tv where tv.email = :email";
            trans.begin();
            Query query = ss.createQuery(hql);
            query.setString("email", email);
            Thanhvien mem = (Thanhvien) query.uniqueResult();
            dskq.add(mem.getTenDangNhap());
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(newpass.getBytes());
            BigInteger dis = new BigInteger(1, md5.digest());
            //byte []dis=md5.digest();
            newpass = dis.toString(16);
            mem.setMatKhau(newpass);
            ss.merge(mem);
            ss.flush();
            trans.commit();
        } catch (Exception ex) {
            ssFac.close();
            dskq = null;
        }
        ssFac.close();
        return dskq;
    }

    public static Boolean changePass(String username, String oldPass, String newpass) {
        Boolean kq = true;
        SessionFactory ssFac = HibernateUtil.getSessionFactory();
        try {
            Session ss = ssFac.openSession();
            Transaction trans = ss.getTransaction();
            String hql = "from Thanhvien tv where tv.tenDangNhap = :username";
            trans.begin();
            Query query = ss.createQuery(hql);
            query.setString("username", username);
            Thanhvien mem = (Thanhvien) query.uniqueResult();

            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(oldPass.getBytes());
            BigInteger dis = new BigInteger(1, md5.digest());
            //byte []dis=md5.digest();
            oldPass = dis.toString(16);

            if (mem.getMatKhau().equals(oldPass)) {
                md5 = MessageDigest.getInstance("MD5");
                md5.update(newpass.getBytes());
                dis = new BigInteger(1, md5.digest());
                //byte []dis=md5.digest();
                newpass = dis.toString(16);
                mem.setMatKhau(newpass);
                ss.merge(mem);
            } else {
                kq = false;
            }
            ss.flush();
            trans.commit();
        } catch (Exception ex) {
            ssFac.close();
            kq = false;
        }
        ssFac.close();
        return kq;
    }

    public static String getRandomString(int loai, int dodai) {
        ////////Code ho tro lay chu ngau nhien, phat trien boi Congdongjava - Tran Huy
        //Loai : kieu ran dom
        //0 : ngau nhien chi cac chu cai thuong
        //1 : ngau nhien chi cac chu cai hoa
        //2 : ngau nhien ca chu hoa va thuong
        //3 : ngau nhien chu va so
        String ketqua = "";
        String hoa = "QWERTYUIOPASDFGHJKLZXCVBNM";
        String thuong = hoa.toLowerCase();
        String so = "1234567890";
        String randomchuoi = "";
        if (loai > 3 || loai < 0) {
            ketqua = "Loai khong hop le, cho phep tu 0 - 3";
        } else if (loai == 0) {
            randomchuoi = thuong;
        } else if (loai == 1) {
            randomchuoi = hoa;
        } else if (loai == 2) {
            randomchuoi = hoa + thuong;
        } else if (loai == 3) {
            randomchuoi = hoa + thuong + so;
        }
        for (int i = 0; i < dodai; i++) {
            int temp = (int) Math.round(Math.random() * randomchuoi.length());
            ketqua += randomchuoi.charAt(temp);
        }
        return ketqua;
    }

    public static Boolean isNumber(String str) {
        Boolean kq = true;
        char[] arr = str.toCharArray();
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] < '0' || arr[i] > '9') {
                kq = false;
            }
        }
        return kq;
    }

    public static Boolean ban_user(Thanhvienvipham tvvp) {
        Boolean kq = true;
        SessionFactory ssFac = HibernateUtil.getSessionFactory();
        Session ss = ssFac.openSession();
        Transaction trans = ss.getTransaction();
        try {
            trans.begin();
            String hql = "from Thanhvienvipham tvvp where tvvp.ngayHetHan > current_date() and tvvp.thanhvien.tenDangNhap = :username";
            Query query = ss.createQuery(hql);
            query.setString("username", tvvp.getThanhvien().getTenDangNhap());
            Thanhvienvipham tvvp2 = new Thanhvienvipham();
            tvvp2 = (Thanhvienvipham) query.uniqueResult();
            if (tvvp2 != null) {
                tvvp2.setNgayHetHan(tvvp.getNgayHetHan());
                tvvp2.setLyDo(tvvp.getLyDo());
                ss.merge(tvvp2);
            } else {
                ss.merge(tvvp);
            }
            ss.flush();
            trans.commit();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            kq = false;
        } finally {
            ssFac.close();
            return kq;
        }
    }

    public static Boolean unban_user(String username) {
        Boolean kq = true;
        SessionFactory ssFac = HibernateUtil.getSessionFactory();
        Session ss = ssFac.openSession();
        Transaction trans = ss.getTransaction();
        try {
            trans.begin();
            String hql = "from Thanhvienvipham tvvp where tvvp.ngayHetHan > current_timestamp() and tvvp.thanhvien.tenDangNhap = :username";
            Query query = ss.createQuery(hql);
            query.setString("username", username);
            Thanhvienvipham tvvp = new Thanhvienvipham();
            tvvp = (Thanhvienvipham) query.uniqueResult();
            tvvp.setNgayHetHan(new java.util.Date());
            ss.merge(tvvp);
            ss.flush();
            trans.commit();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            kq = false;
        } finally {
            ssFac.close();
            return kq;
        }
    }

    public static ArrayList<Thanhtoan> getAllThanhToanInformation() {
        ArrayList<Thanhtoan> dsthanhtoan = new ArrayList<Thanhtoan>();
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            Transaction trans = session.getTransaction();
            trans.begin();
            String hql = "from Thanhtoan";
            Query query = session.createQuery(hql);
            dsthanhtoan = (ArrayList<Thanhtoan>) query.list();
            trans.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return dsthanhtoan;
    }

    public static ArrayList<Thanhvienvipham> getUserBanned(String chuoitimkiem) {
        ArrayList<Thanhvienvipham> dstvvp = new ArrayList<Thanhvienvipham>();
        try {
            String hql = "";
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            Transaction trans = session.getTransaction();
            trans.begin();
            if (chuoitimkiem.equals("")) {
                hql = "from Thanhvienvipham tvvp where tvvp.ngayHetHan > current_timestamp()";
            } else {
                hql = "from Thanhvienvipham tvvp where tvvp.thanhvien.tenDangNhap like :chuoitimkiem and tvvp.ngayHetHan > current_timestamp()";
            }
            Query query = session.createQuery(hql);
            if (!chuoitimkiem.equals("")) {
                query.setString("chuoitimkiem", "%" + chuoitimkiem + "%");
            }
            dstvvp = (ArrayList<Thanhvienvipham>) query.list();
            trans.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return dstvvp;
    }

    public static ArrayList<Thanhvien> getUserNotBan(String chuoitimkiem) {
        ArrayList<Thanhvien> list = null;
        try {
            String hql = "";
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            Transaction trans = session.getTransaction();
            trans.begin();
            if (chuoitimkiem.equals("")) {
                hql = "from Thanhvien tv where tv.tenDangNhap not in "
                        + "("
                        + "select tvvp.thanhvien.tenDangNhap from Thanhvienvipham tvvp where tvvp.ngayHetHan > current_timestamp()"
                        + ")";
            } else {
                hql = "from Thanhvien tv where tv.tenDangNhap like :chuoitimkiem and tv.tenDangNhap not in "
                        + "("
                        + "select tvvp.thanhvien.tenDangNhap from Thanhvienvipham tvvp where tvvp.ngayHetHan > current_timestamp()"
                        + ")";
            }
            Query query = session.createQuery(hql);
            if (!chuoitimkiem.equals("")) {
                query.setString("chuoitimkiem", "%" + chuoitimkiem + "%");
            }
            list = (ArrayList<Thanhvien>) query.list();
            trans.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return list;
    }

    public static ArrayList<Chitietdaugia> userBidHistory(String username) {
        ArrayList<Chitietdaugia> dskq = new ArrayList<Chitietdaugia>();
        SessionFactory ssFac = HibernateUtil.getSessionFactory();
        Session ss = ssFac.openSession();
        Transaction trans = ss.getTransaction();
        try {
            trans.begin();
            String hql = "from Chitietdaugia ctdg where ctdg.thanhvien.tenDangNhap = :username";
            Query query = ss.createQuery(hql);
            query.setString("username", username);
            dskq = (ArrayList<Chitietdaugia>) query.list();
            ss.flush();
            trans.commit();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        } finally {
            ssFac.close();
            return dskq;
        }
    }

    public static String IsBanUser(String username) {
        String kq = "";
        Thanhvienvipham tvvp = new Thanhvienvipham();
        SessionFactory ssFac = HibernateUtil.getSessionFactory();
        Session ss = ssFac.openSession();
        Transaction trans = ss.getTransaction();
        try {
            trans.begin();
            String hql = "from Thanhvienvipham tvvp where tvvp.ngayHetHan > current_timestamp() and tvvp.thanhvien.tenDangNhap = :username";
            Query query = ss.createQuery(hql);
            query.setString("username", username);
            tvvp = (Thanhvienvipham) query.uniqueResult();
            if (tvvp != null) {
                kq = tvvp.getNgayHetHan().toString();
            }
            ss.flush();
            trans.commit();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        } finally {
            ssFac.close();
            return kq;
        }
    }
}
